package com.lancoo.answer.util;

import android.content.Context;
import android.text.Html;
import android.text.Layout;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.AlignmentSpan;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;

import com.ivan.GlideEngine;
import com.ivan.easyphotos.EasyPhotos;
import com.lancoo.answer.R;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.TaskState;
import com.lancoo.answer.model.bean.Child;
import com.lancoo.answer.model.bean.Item;
import com.lancoo.answer.model.entity.TaskControlBean;
import com.lancoo.answer.util.paperUtils.ChildRightOrWrongJudgeUtils;
import com.lancoo.answer.widget.span.CenteredImageSpan;
import com.lancoo.answer.widget.span.FillAnwerSpan;
import com.lancoo.answer.widget.span.UrlImageSpan;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by pengmi on 2022/3/24 13:51
 * Description:小题题干处理工具类
 */
public class RichTxtDealTuils {

    private static final String firstEm="\t\t\t\t";

    /**
     * 显示小题原题干样式
     */
    public static void getNormalChildBody(TextView textView, Child child,boolean enableShowChildAsk){
        if(child.getItemList()==null){
            return;
        }
//        child.setChildAsk("-Were they late for the play? <P class=\\\"tq-p\\\";>-Not really. As soon as they ____ themselves in their seats in the theatre, the curtain ____. </P>");
        String sortIndex=child.getItemList().get(0).getSortIndex();//小题序号
        String childAsk=child.getChildAsk();//小题原始题干
        String sortStr=sortIndex+". ";
        SpannableStringBuilder ssb_childBody=new SpannableStringBuilder();
        if(!enableShowChildAsk){
            ssb_childBody.append(addMarkTagImg(textView.getContext(),child));
            ssb_childBody.append(sortStr);
            textView.setText(ssb_childBody);
            return;
        }
        boolean isIndentChildAsk = child.getIsIndentChildAsk();//是否需要缩进
        if(childAsk==null){
            childAsk="";
        }
        if(TextUtils.isEmpty(childAsk)){
            ssb_childBody.append(addMarkTagImg(textView.getContext(),child));
            ssb_childBody.append(sortStr);
            textView.setText(ssb_childBody);
            return;
        }
        childAsk=childAsk.replace("_","<u>&nbsp;&nbsp;</u>");//将小题原始题干中的下划线替换成u标签
        Document parse = Jsoup.parse(childAsk);
        List<Node> nodeList = parse.body().childNodes();//获取到全部的内容文本标签
        for (Node node : nodeList){
            String nodeContent = node.outerHtml();
            if(TextUtils.isEmpty(nodeContent)){
                continue;
            }
            String align = node.attr("align");
            String nodeName = node.nodeName();
            boolean isNeedAppendLineFeed=false;//是否需要拼接换行符
            Layout.Alignment tag=Layout.Alignment.ALIGN_NORMAL;
            boolean isPTab=false;
            if(!TextUtils.isEmpty(nodeName)&&TextUtils.equals("p",nodeName)){//如果是p标签，拼接内容之前判断需不需要先拼接换行符
                isPTab=true;
                if(TextUtils.isEmpty(ssb_childBody)){
                    if(!TextUtils.isEmpty(align)){
                        isNeedAppendLineFeed=true;
                    }
                }else{
                    isNeedAppendLineFeed=true;
                }
                //如果包含有对齐属性，需特殊处理
                if (!TextUtils.isEmpty(align)) {
                    switch (align.toLowerCase()) {
                        case "center":
                            tag = Layout.Alignment.ALIGN_CENTER;
                            break;
                        case "right":
                            tag = Layout.Alignment.ALIGN_OPPOSITE;
                            break;
                        default:
                            tag = Layout.Alignment.ALIGN_NORMAL;

                    }
                }
            }
            if(TextUtils.isEmpty(ssb_childBody)){//如果内容为空，增加小题序号显示
                if(!TextUtils.isEmpty(sortIndex)){
                    ssb_childBody.append(addMarkTagImg(textView.getContext(),child));
                    ssb_childBody.append(sortStr);
                }
            }
            if(isNeedAppendLineFeed&&!TextUtils.isEmpty(ssb_childBody)){
                ssb_childBody.append("\n");
            }
            if(node instanceof Element){
                if(isPTab){
                    ((Element) node).tagName("span");
                    if(isIndentChildAsk&&tag==Layout.Alignment.ALIGN_NORMAL){
                        ssb_childBody.append(firstEm);
                    }
                }
                SpannableString spannableString = new SpannableString(Html.fromHtml(node.outerHtml()));
                if(tag!=Layout.Alignment.ALIGN_NORMAL){
                    AlignmentSpan.Standard alignmentSpan = new AlignmentSpan.Standard(tag);
                    spannableString.setSpan(alignmentSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
                ssb_childBody.append(spannableString);

            }else{
                if(node.outerHtml().startsWith(" "));
                ssb_childBody.append(" ");
                ssb_childBody.append(Html.fromHtml(node.outerHtml()));
//                ssb_childBody.append(Html.fromHtml(node.outerHtml()));
            }

        }
        underLineAndImgsDeal(ssb_childBody,textView);
    }

    private static SpannableString addMarkTagImg(Context mContext,Child child){
        if(!child.getItemList().get(0).getItemMark()||ConstantBean.Companion.getTaskState()!= TaskState.TRAINING){
            return new SpannableString("");
        }
        SpannableString spannableString=new SpannableString("123 ");
        spannableString.setSpan(new CenteredImageSpan(mContext, R.drawable.ev_vector_question_yellow),0,3,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableString;
    }
    public static SpannableString addMarkTagImg(Context mContext,Item item){
        if(!item.getItemMark()||ConstantBean.Companion.getTaskState()!= TaskState.TRAINING){
            return new SpannableString("");
        }
        SpannableString spannableString=new SpannableString("123 ");
        spannableString.setSpan(new CenteredImageSpan(mContext, R.drawable.ev_vector_question_yellow),0,3,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableString;
    }


    /**
     * 下划线与图片标签 处理
     * @param spannable spanned
     * @param textView tv
     */
    private static void underLineAndImgsDeal(Spanned spannable,TextView textView){
        SpannableString spannableString = new SpannableString(spannable);
        UnderlineSpan[] spans = spannableString.getSpans(0, spannableString.length(), UnderlineSpan.class);


        ImageSpan[] imageSpans = spannableString.getSpans(0, spannableString.length(), ImageSpan.class);
        FillAnwerSpan[] fillSpans = spannableString.getSpans(0, spannableString.length(), FillAnwerSpan.class);
        if(fillSpans!=null){
            for (FillAnwerSpan span:fillSpans){
                spannableString.removeSpan(span);
            }
        }
        ArrayList<String> imgList=new ArrayList<>();
        for (int i = 0; i < imageSpans.length; i++) {
            ImageSpan imageSpan = imageSpans[i];
            int spanStart = spannableString.getSpanStart(imageSpan);
            int spanEnd = spannableString.getSpanEnd(imageSpan);
            if(imageSpan.getSource()==null){
                continue;
            }
            String source = imageSpan.getSource().replace("<u>  </u>","_");
            imgList.add(source);
            final int position=i;
            UrlImageSpan urlImageSpan=new UrlImageSpan(textView.getContext(),source,textView);
            ClickableSpan clickableSpan=new ClickableSpan() {
                @Override
                public void onClick(@NonNull View widget) {
                    EasyPhotos.startPreviewPaths((FragmentActivity) widget.getContext(),
                            GlideEngine.getInstance(), imgList,true,position);
                }
            };
            spannableString.setSpan(clickableSpan, spanStart , spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannableString.setSpan(urlImageSpan, spanStart , spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        for (UnderlineSpan span : spans) {
            int spanStart = spannableString.getSpanStart(span);
            int spanEnd = spannableString.getSpanEnd(span);
            CharSequence charSequence = spannableString.subSequence(spanStart, spanEnd);
            String content = charSequence.toString();
            String[] split = content.split(" ");
            if(TextUtils.equals(content,"  ")){
                continue;
            }
            if (split.length > 1) {
                int addLength = 0;
                for (int j = 0; j < split.length; j++) {
                    String subAsk = split[j] + (j < split.length - 1 ? " " : "");
                    FillAnwerSpan fillAnwerSpan = new FillAnwerSpan(textView.getContext(), textView.getPaint());
                    fillAnwerSpan.setDrawableLineType(3);
                    fillAnwerSpan.setUnderLine(true);
                    fillAnwerSpan.setmText(subAsk);
                    spannableString.setSpan(fillAnwerSpan, spanStart + addLength, spanStart + addLength + subAsk.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    addLength += subAsk.length();
                }
            } else {

                int subIndex=0;
                StringBuilder fillContent=new StringBuilder();
                for (char c:charSequence.toString().toCharArray()){

                    boolean chineseCharacter = isChineseCharacter(c);
                    fillContent.append(c);
                    if(chineseCharacter){
                        FillAnwerSpan fillAnwerSpan = new FillAnwerSpan(textView.getContext(), textView.getPaint());
                        fillAnwerSpan.setDrawableLineType(3);
                        fillAnwerSpan.setUnderLine(true);
                        fillAnwerSpan.setmText(fillContent.toString());
                        spannableString.setSpan(fillAnwerSpan, spanStart+subIndex+1-fillContent.length(), spanStart+subIndex+1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        fillContent=new StringBuilder();
                    }else {
                        if(subIndex==charSequence.length()-1){
                            FillAnwerSpan fillAnwerSpan = new FillAnwerSpan(textView.getContext(), textView.getPaint());
                            fillAnwerSpan.setDrawableLineType(3);
                            fillAnwerSpan.setUnderLine(true);
                            fillAnwerSpan.setmText(fillContent.toString());
                            spannableString.setSpan(fillAnwerSpan, spanStart+subIndex+1-fillContent.length(), spanStart+subIndex+1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        }
                    }
                    subIndex++;
                }
            }


        }

        int endIndex = spannableString.length();
        for (int i = spannableString.length() - 1; i >= 0; i--) {
            char c = spannableString.charAt(i);
            if (!TextUtils.isEmpty(("" + c).trim())) {
                break;
            }
            endIndex = i;
        }
        textView.setText(spannableString.subSequence(0, endIndex));
    }


    /**
     * 判断一个字符是否是中文
     * */
    public static boolean isChineseCharacter(char c) {
        return c >= 0x4E00 && c <= 0x9FA5;// 根据字节码判断
    }

    /**
     * 显示填空题型查看原题样式，参考答案回填到填空处
     */
    public static void getFillOrginalAnswerChildAsk(TextView tv, Child child, boolean enableShowQueseBody) {
        String queseBody="";
        if(enableShowQueseBody){
            queseBody=child.getChildAsk();
        }
        String orderIndexStr=child.getItemList().get(0).getSortIndex();
        List<Item> itemList=child.getItemList();
        Log.e("fillAnswer", "original:" + queseBody);
        String tag = "______";
        String tag3="&margingpaddingtop&";
        String tagBr="$brrb$";
        if(queseBody==null){
            queseBody="";
        }
        String replaceStr = queseBody.replace("<BR>",tagBr);
        Document document = Jsoup.parse(replaceStr);
        Elements elements_p = document.select("P");
        for (Element element : elements_p) {
            element.tagName("span");
            element.append(tagBr);
        }
        Elements znbkblank = document.getElementsByClass("znbkblank");
        for (Element element:znbkblank){
            String html = element.html();
            if(TextUtils.isEmpty(html)||TextUtils.isEmpty(html.trim())){
                element.text(tag);
            }
        }
        String content = document.body().text().replace(tagBr,"\n"+tag3+"\n");
        Log.e("fillAnswer","第一次处理过后的:"+content);
        String bodyStr = orderIndexStr + ". " + content;
        String[] split = bodyStr.split(tag);
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
        int showType=2;
        for(int i = 0; i < split.length; i++) {
            spannableStringBuilder.append(split[i]);
            if(itemList==null){
                continue;
            }
            if (i < itemList.size()) {
                Item item = itemList.get(i);
                spannableStringBuilder.append("");
                String fillContent=item.getItemAnswer();
                if(fillContent==null){
                    fillContent="";
                }
                String[] splitEmpty = fillContent.replace("$/","或").split(" ");
                for (int j = 0; j < splitEmpty.length; j++) {
                    String answerStr = splitEmpty[j];
                    if (answerStr.length() > 20) {
                        int splitLength = (answerStr.length() - 1) / 20 + 1;
                        for (int k = 0; k < splitLength; k++) {
                            String subFillContent = answerStr.substring(k * 20, Math.min((k + 1) * 20, answerStr.length())) +
                                    (j < splitEmpty.length - 1 && k == splitLength - 1 ? " " : "");
                            SpannableString spannableString = new SpannableString(subFillContent);
                            FillAnwerSpan fillAnwerSpan = new FillAnwerSpan(tv.getContext(), tv.getPaint());
                            fillAnwerSpan.setmText(subFillContent);
                            fillAnwerSpan.setStartFill(j == 0 && k == 0);
                            fillAnwerSpan.setEndFill(j == splitEmpty.length - 1 && k == splitLength - 1);
                            fillAnwerSpan.setDrawableLineType(showType);
                            spannableString.setSpan(fillAnwerSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            spannableStringBuilder.append(spannableString);
                        }
                    } else {
                        String subFillContent = splitEmpty[j] + (j < splitEmpty.length - 1 ? " " : "");
                        SpannableString spannableString = new SpannableString(subFillContent);
                        FillAnwerSpan fillAnwerSpan = new FillAnwerSpan(tv.getContext(), tv.getPaint());
                        fillAnwerSpan.setmText(subFillContent);
                        fillAnwerSpan.setStartFill(j == 0);
                        fillAnwerSpan.setEndFill(j == splitEmpty.length - 1);
                        fillAnwerSpan.setDrawableLineType(showType);
                        spannableString.setSpan(fillAnwerSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        spannableStringBuilder.append(spannableString);
                    }

                }
                spannableStringBuilder.append("");
            }
        }
        String newStr = spannableStringBuilder.toString();
        String[] split1 = newStr.split(tag3);
        if(split1.length>1){
            int startIndex=0;
            for (int i = 0; i <split1.length -1; i++) {
                try {
                    startIndex+=split1[i].length();
                    int endIndex1=startIndex+tag3.length();
                    spannableStringBuilder.setSpan(new ForegroundColorSpan(0x00000000),startIndex,endIndex1,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableStringBuilder.setSpan(new AbsoluteSizeSpan(1,false),startIndex,endIndex1,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    startIndex=endIndex1;
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        underLineAndImgsDeal(spannableStringBuilder,tv);
    }


    /**
     * 查看作答时,填空题作答内容在题干中回显处理
     *
     * @param tv textView
     * @param child Child
     */
    public static void getFillLookingAnswerChildAsk(TextView tv, Child child, boolean enableShowQueseBody) {
        String queseBody="";
        if(enableShowQueseBody){
            queseBody=child.getChildAsk();
        }
        String orderIndexStr=child.getItemList().get(0).getSortIndex();
        List<Item> itemList=child.getItemList();
        Log.e("fillAnswer", "original:" + queseBody);
        String tag = "______";
        String tagBr="$brrb$";
        String tag3="&margingpaddingtop&";
        if(queseBody==null){
            queseBody="";
        }
        String replaceStr = queseBody.replace("<BR>",tagBr);
        Document document = Jsoup.parse(replaceStr);
        Elements elements_p = document.select("P");
        for (Element element : elements_p) {
            element.tagName("span");
            element.append(tagBr);
        }
        Elements znbkblank = document.getElementsByClass("znbkblank");
        for (Element element:znbkblank){
            String html = element.html();
            if(TextUtils.isEmpty(html)||TextUtils.isEmpty(html.trim())){
                element.text(tag);
            }
        }
        String content = document.body().text().replace(tagBr,"\n"+tag3+"\n");
        Log.e("fillAnswer","第一次处理过后的:"+content);
        String bodyStr = orderIndexStr + ". " + content;
        String[] split = bodyStr.split(tag);
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
        for(int i = 0; i < split.length; i++) {
            String splitContent = split[i];
            SpannableString sb_Content=new SpannableString(splitContent);
            spannableStringBuilder.append(sb_Content);
            if(itemList==null){
                continue;
            }
            if (i < itemList.size()) {
                Item item = itemList.get(i);
                String scanImagePath = item.getScanImagePath();
                if(!TextUtils.isEmpty(scanImagePath)){
                    ImageSpan span=new UrlImageSpan(tv.getContext(),item.getScanImagePath(),tv);
                    SpannableString spannableString=new SpannableString(scanImagePath);
                    spannableString.setSpan(span,0,scanImagePath.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableStringBuilder.append(spannableString);
                    continue;
                }
                int showType;
                TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
                if(taskControlBean!=null&&taskControlBean.getExpired()){
                    showType=4;
                }else{
                    if (ChildRightOrWrongJudgeUtils.judateItemAnwerState(item) == 1) {
                        showType = 2;
                    } else {
                        showType = 1;
                    }
                }
                spannableStringBuilder.append("");
                String fillContent = item.getStuAnswer();
                if(TextUtils.isEmpty(fillContent)){
                    fillContent="未填写";
                }
                if(fillContent==null){
                    fillContent="";
                }
                String[] splitEmpty = fillContent.split(" ");
                Log.e("fillAnswer","fillContent:"+fillContent);
                for (int j = 0; j < splitEmpty.length; j++) {
                    String answerStr = splitEmpty[j];
                    Log.e("fillAnswer",j+"answerStr:"+answerStr);
                    if (answerStr.length() > 20) {
                        int splitLength = (answerStr.length() - 1) / 20 + 1;
                        for (int k = 0; k < splitLength; k++) {
//                            String subFillContent=splitEmpty[j]+(j<splitEmpty.length-1?" ":"");
                            String subFillContent = answerStr.substring(k * 20, Math.min((k + 1) * 20, answerStr.length())) +
                                    (j < splitEmpty.length - 1 && k == splitLength - 1 ? " " : "");
                            SpannableString spannableString = new SpannableString(subFillContent);
                            FillAnwerSpan fillAnwerSpan = new FillAnwerSpan(tv.getContext(), tv.getPaint());
                            fillAnwerSpan.setmText(subFillContent);
                            fillAnwerSpan.setStartFill(j == 0 && k == 0);
                            fillAnwerSpan.setEndFill(j == splitEmpty.length - 1 && k == splitLength - 1);
                            fillAnwerSpan.setDrawableLineType(showType);
                            spannableString.setSpan(fillAnwerSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            spannableStringBuilder.append(spannableString);
                        }
                    } else {
                        String subFillContent = splitEmpty[j] + (j < splitEmpty.length - 1 ? " " : "");
                        SpannableString spannableString = new SpannableString(subFillContent);
                        FillAnwerSpan fillAnwerSpan = new FillAnwerSpan(tv.getContext(), tv.getPaint());
                        fillAnwerSpan.setmText(subFillContent);
                        fillAnwerSpan.setStartFill(j == 0);
                        fillAnwerSpan.setEndFill(j == splitEmpty.length - 1);
                        fillAnwerSpan.setDrawableLineType(showType);
                        spannableString.setSpan(fillAnwerSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        spannableStringBuilder.append(spannableString);
                    }

                }
                spannableStringBuilder.append("");
            }

        }
        String newStr = spannableStringBuilder.toString();
        String[] split1 = newStr.split(tag3);
        if(split1.length>1){
            int startIndex=0;
            for (int i = 0; i <split1.length -1; i++) {
                try {
                    startIndex+=split1[i].length();
                    int endIndex1=startIndex+tag3.length();
                    spannableStringBuilder.setSpan(new ForegroundColorSpan(0x00000000),startIndex,endIndex1,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableStringBuilder.setSpan(new AbsoluteSizeSpan(1,false),startIndex,endIndex1,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    startIndex=endIndex1;
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        underLineAndImgsDeal(spannableStringBuilder,tv);
    }

    public static void loadAskContent(TextView textView,String content){

        String replace = content.replace("_", "<u>&nbsp;</u>");
        textView.setText(Html.fromHtml(replace));

    }
}
